package client

import (
	"context"
	api "dfs/server/master/api/client"
	"dfs/server/master/config"
	"dfs/server/master/core/fs"
)

type ClientService struct{}

func (c *ClientService) NewFile(ctx context.Context, req *api.NewFileReq) (*api.NewFileResp, error) {
	blocks, ok := fs.Put(req.Url, int(req.Length))
	if !ok {
		return &api.NewFileResp{Success: false, Message: "创建文件失败"}, nil
	}
	return &api.NewFileResp{Success: true, Message: "创建文件成功", Blocks: blocks, BlockSize: config.BlockSize}, nil
}

func (c *ClientService) GetBlocks(ctx context.Context, req *api.GetBlocksReq) (*api.GetBlocksResp, error) {
	blocks, ok := fs.Get(req.Url)
	if !ok {
		return &api.GetBlocksResp{Success: false, Message: "目标是文件夹"}, nil
	}
	return &api.GetBlocksResp{Success: true, Message: "获取文件成功", Blocks: blocks}, nil
}

func (c *ClientService) Mkdir(ctx context.Context, req *api.MkdirReq) (*api.GenericResp, error) {
	if fs.Mkdir(req.Url) {
		return &api.GenericResp{Success: true, Message: "创建成功"}, nil
	} else {
		return &api.GenericResp{Success: false, Message: "创建失败"}, nil
	}
}

func (c *ClientService) Delete(ctx context.Context, req *api.DeleteReq) (*api.GenericResp, error) {
	if fs.Delete(req.Url) {
		return &api.GenericResp{Success: true, Message: "删除成功"}, nil
	} else {
		return &api.GenericResp{Success: false, Message: "删除失败"}, nil
	}
}
